package it.uniroma2.controller;

import java.net.InetSocketAddress;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.yammer.metrics.MetricFilter;
import com.yammer.metrics.MetricRegistry;
import com.yammer.metrics.graphite.Graphite;
import com.yammer.metrics.graphite.GraphiteReporter;

public class ControllerContextListener implements ServletContextListener {

	public static String metricsRegistryName = "ControllerApp"
			+ UUID.randomUUID().toString();

	public static final MetricRegistry mRegistry = new MetricRegistry(
			metricsRegistryName);
	
	public static CloudConfig cloudConfig = new CloudConfig();

	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("contextInitialized");
		String monAddress = cloudConfig.getMonitoringAddress();
		System.out.println("Discover monitoring Address: " + monAddress);
		InstanceCounterMonitor instanceCounterMonitor = new InstanceCounterMonitor(cloudConfig);
		ReporterMonitor reporterMonitor = new ReporterMonitor();
		LoadChecker loadChecker = new LoadChecker();
		LatencyChecker latencyChecker = new LatencyChecker();
		try {

			final Graphite graphite = new Graphite(new InetSocketAddress(
					monAddress, 2023));
			final GraphiteReporter reporter = GraphiteReporter
					.forRegistry(mRegistry).prefixedWith("master.controller")
					.convertRatesTo(TimeUnit.SECONDS)
					.convertDurationsTo(TimeUnit.MILLISECONDS)
					.filter(MetricFilter.ALL).build(graphite);

			reporter.start(10, TimeUnit.SECONDS);
			Controller.getInstance();					
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("contextDestroyed");
	}
	
	public static CloudConfig getCloudConfig(){
		return cloudConfig;
	}

}
